package org.lboot.flow.module.define;

import cn.hutool.core.lang.Validator;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import org.hibernate.Hibernate;
import org.lboot.flow.constant.FlowNodeTypeConst;
import org.lboot.flow.model.FlowModel;
import org.lboot.flow.model.node.*;
import org.lboot.jpa.converter.JpaListObjectConverter;
import org.lboot.jpa.entity.BaseEntity;

import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * @author kindear
 * 流程定义实体类
 */
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
@Table(name = "flow_define")
@ApiModel(value = "流程定义实体类")
public class FlowDefine extends BaseEntity implements Serializable {

    @ApiModelProperty(value = "流程图标")
    @Column(name = "flow_icon")
    String flowIcon;

    @ApiModelProperty("流程分组")
    @Column(name = "flow_group")
    String flowGroup;

    @ApiModelProperty("流程定义编码")
    @Column(name = "flow_code")
    String flowCode;

    @ApiModelProperty("流程名称")
    @Column(name = "flow_name")
    String flowName;

    @ApiModelProperty("流程描述")
    @Column(name = "description",length = 512)
    String description;

    @Convert(converter = JpaListObjectConverter.class)
    @Column(name = "node_list",columnDefinition = "TEXT")
    List<BaseModel> nodeList;

    @ApiModelProperty(value = "流程定义类型")
    @Column(name = "flow_define_type")
    String flowDefineType;

    @ApiModelProperty(value = "流程定义",notes = "JSON字符串")
    @Column(name = "flow_define",columnDefinition = "TEXT")
    String flowDefine;

    @ApiModelProperty(value = "表单定义",notes = "JSON字符串")
    @Column(name = "flow_widgets",columnDefinition = "TEXT")
    String flowWidgets;

    @ApiModelProperty(value = "流程状态",notes = "1 正常 0 无法访问")
    @Column(name = "status")
    Integer status;

    @SneakyThrows
    public BaseModel getNodeModel(String nodeId) {
        return FlowModel.getNodeModel(this.nodeList, nodeId);
    }

    /**
     * 获取开始节点模型
     * @return
     */
    @JsonIgnore
    public StartModel getStartModel() {

        StartModel model = (StartModel) getNodeModel("start");
        if (Validator.isEmpty(model.getEnableAll())){
            model.setEnableAll(true);
        }
        return model;
    }

}
